package net.forsalemall.android;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.droidfu.widgets.WebImageView;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.Utils;

public class SuperCategoriesActivity extends ListActivity {

	private static final int START_SPEECH_TO_TEXT = 102;

	private List<ListItem> items;
	private EfficientAdapter adap;
	private String superCategoryData;
	private JSONArray jCategories;
	private String countryCode;
	
	private RelativeLayout searchLayout;

	private Action showSearchAction;
	private Action hideSearchAction;
	private Action voiceSearchAction;
	
	private Button searchButton;
	private TextView searchTextView;
	
	private boolean voiceSearchEnabled;

	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			setContentView(R.layout.super_category);
			countryCode = getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE);
			searchLayout = (RelativeLayout) findViewById(R.id.search_layout);
			searchLayout.setVisibility(View.GONE);
			searchButton = (Button) findViewById(R.id.search_button);
			searchTextView = (TextView) findViewById(R.id.search_field);
			
			final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
			actionBar.setTitle(getString(R.string.title_categories));
			actionBar.setHomeAction(new Action() {

				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});
			showSearchAction = new Action() {
				public void performAction(View view) {
					actionBar.removeAction(this);
					actionBar.addAction(hideSearchAction);
					searchLayout.setVisibility(View.VISIBLE);
				}

				public int getDrawable() {
					return R.drawable.ic_menu_search;
				}
			};
			hideSearchAction = new Action() {
				public void performAction(View view) {
					actionBar.removeAction(this);
					actionBar.addAction(showSearchAction);
					searchLayout.setVisibility(View.GONE);
				}

				public int getDrawable() {
					return R.drawable.ic_menu_search_hide;
				}
			};
			voiceSearchAction = new Action() {
				public void performAction(View view) {
					startSpeechToTextActivity();
				}

				public int getDrawable() {
					return R.drawable.ic_menu_microphone;
				}
			};
			actionBar.addAction(showSearchAction);
			actionBar.setDisplayHomeAsUpEnabled(true);

			PackageManager pm = getPackageManager();
			List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
					RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
			voiceSearchEnabled = (activities.size() > 0);
			if (voiceSearchEnabled) {
				actionBar.addAction(voiceSearchAction);
			}
			
			searchButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					startSearchActivity(searchTextView.getText().toString());
				}
			});


			items = new ArrayList<ListItem>();

			// dirName = jConstants
			// .getString(Constants.CATEGORY_IMAGE_THUMB_DIR_CONSTANT_NAME);
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;

				protected void onPreExecute() {
					try {
						progressDialog = Utils.getProgressDialog(
								SuperCategoriesActivity.this, null,
								getString(R.string.loading));
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						int supCatType = getIntent().getIntExtra(
								Constants.KEY_CATEGORY_TYPE,
								Constants.TYPE_NORMAL_CAT);
						if (supCatType == Constants.TYPE_FEATURE_CAT) {
							superCategoryData = HttpUtils
									.getServiceCategoriesData(countryCode);
						} else {
							superCategoryData = HttpUtils
									.getForsaleCategoriesData(countryCode);
						}
						jCategories = new JSONArray(superCategoryData);
						if (jCategories != null) {
							JSONObject jo;
							String fileName;
							for (int i = 0; i < jCategories.length(); i++) {
								jo = jCategories.getJSONObject(i);
								fileName = jo.getString("img_file_name");
								if (fileName != null && fileName.length() > 3) {
									items.add(new ListItem(
											jo.getInt("sup_cat_id"),
											jo.getInt("ad_count"),
											Utils.getDecodedString(jo
													.getString("sup_cat_name")),

											HttpUtils.getFileUrl(
													Constants
															.getSuperCatImgThumbDirName(),
													fileName), jo.getJSONArray(
													"categories").toString()));
								} else {
									items.add(new ListItem(
											jo.getInt("sup_cat_id"),
											jo.getInt("ad_count"),
											Utils.getDecodedString(jo
													.getString("sup_cat_name")),

											HttpUtils.getFileUrl(
													Constants
															.getDefaultImgDirName(),
													Constants
															.getDefaultImgFileName()),
											jo.getJSONArray("categories")
													.toString()));
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						adap = new EfficientAdapter(
								SuperCategoriesActivity.this);
						setListAdapter(adap);
						progressDialog.dismiss();
						
//						//
//						startSearchActivity("سيارات");
//						//
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		try {
			Intent intent = new Intent(this, CategoriesActivity.class);
			intent.putExtra(Constants.KEY_COUNTRY_CODE, countryCode);
			intent.putExtra(Constants.KEY_SUPER_CATEGORY_ID,
					items.get(position).cat_id);
			intent.putExtra(Constants.KEY_SUPER_CATEGORY_NAME,
					items.get(position).title);
			intent.putExtra(Constants.KEY_SUPER_CATEGORY_DATA,
					items.get(position).categoriesData);
			intent.putExtra(
					Constants.KEY_AD_TYPE,
					getIntent().getIntExtra(Constants.KEY_AD_TYPE,
							Constants.TYPE_NORMAL_AD));
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class ListItem {
		private int cat_id;
		private int count;
		private String title;
		private String url;
		private String categoriesData;

		public ListItem(int cat_id, int count, String title, String url,
				String categoriesData) {
			this.cat_id = cat_id;
			this.count = count;
			this.title = title;

			this.url = url;
			this.categoriesData = categoriesData;
		}
	}

	public class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Context context;

		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.category_list_content,
						null);
				holder = new ViewHolder();
				holder.icon = (WebImageView) convertView
						.findViewById(R.id.list_icon);
				holder.title = (TextView) convertView
						.findViewById(R.id.list_title);
				holder.countView = (TextView) convertView
						.findViewById(R.id.list_count_view);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position % 2 == 0) {
				convertView.setBackgroundColor(Constants.BG_EVEN_CELL);
			} else {
				convertView.setBackgroundColor(Constants.BG_ODD_CELL);
			}
			holder.icon.setImageUrl(items.get(position).url);
			holder.icon.loadImage();
			holder.title.setText(items.get(position).title);
			holder.countView
					.setText(Integer.toString(items.get(position).count));
			return convertView;
		}

		class ViewHolder {
			WebImageView icon;
			TextView title;
			TextView countView;

		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}
	}

	private void startSpeechToTextActivity() {
		try {
			Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
					RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speak_now));
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ar-AR");
			intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, "1");
			// intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, "true");
			// intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, "true");
			// intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, "true");

			startActivityForResult(intent, START_SPEECH_TO_TEXT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			if (requestCode == START_SPEECH_TO_TEXT) {
				switch (resultCode) {
				case RESULT_OK:
					ArrayList<String> matches = data
							.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
					if (matches.size() > 0) {
						String text = "";
						for (int i = 0; i < matches.size(); i++) {
							if (i == 0) {
								text = matches.get(i);
							}
//							else {
//								text = text.concat(" ");
//								text = text.concat(matches.get(i));
//							}

						}
//						Utils.showAlertMessage(SuperCategoriesActivity.this,
//								null, text);
						startSearchActivity(text);
					} else {
						Utils.showAlertMessage(SuperCategoriesActivity.this,
								null, getString(R.string.no_result_matched));
					}
					break;
				case RecognizerIntent.RESULT_AUDIO_ERROR:
					Utils.showAlertMessage(SuperCategoriesActivity.this, null,
							getString(R.string.check_audio_setting));
					break;
				case RecognizerIntent.RESULT_CLIENT_ERROR:
					Utils.showAlertMessage(SuperCategoriesActivity.this, null,
							"Client Error");
					break;
				case RecognizerIntent.RESULT_NETWORK_ERROR:
					Utils.showAlertMessage(SuperCategoriesActivity.this, null,
							getString(R.string.go_online));
					break;
				case RecognizerIntent.RESULT_NO_MATCH:
					Utils.showAlertMessage(SuperCategoriesActivity.this, null,
							getString(R.string.no_result_matched));
					break;
				case RecognizerIntent.RESULT_SERVER_ERROR:
					Utils.showAlertMessage(SuperCategoriesActivity.this, null,
							"Google Server Error");
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	private void startSearchActivity(final String searchKey){
		try {
		
			Intent intent = new Intent(SuperCategoriesActivity.this,
					AdsBySearchActivity.class);

			intent.putExtra(Constants.KEY_COUNTRY_CODE,
					getIntent().getStringExtra(Constants.KEY_COUNTRY_CODE));	
			intent.putExtra(Constants.KEY_CATEGORY_ID, getIntent().getIntExtra(Constants.KEY_CATEGORY_ID, 0));
			intent.putExtra(Constants.KEY_CATEGORY_NAME,searchKey);
			intent.putExtra(Constants.KEY_SEARCH_KEY,searchKey);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}